import { Element } from 'diagram-js/lib/model/Types';
import { ElMessage } from 'element-plus';
import { getBusinessObject, is } from 'bpmn-js/lib/util/ModelUtil';
import modelerStore from '@wf/components/bpmnjs/store/modeler';
import editor from '@wf/components/bpmnjs/store/editor';

export interface GlobalVariable {
  id: string;
  name: string;
  itemSubjectRef: string;
  inoutput: string;
  required: string;
}

// 全局变量的增删改查方法
export function getGlobalVariablesValue(element: Element) {
  const businessObject = getBusinessObject(element);
  if(!businessObject.flowElements) {
    return [];
  }
  const variables = businessObject.flowElements.filter((e: Element) => is(e, 'bpmn:DataObject'));
  return variables ?? [];
}

export function setGlobalVariableValue(element: Element, dataObject: GlobalVariable) {
  const store = modelerStore();
  const modeler = store.getModeler;
  const bpmnFactory = modeler.get('bpmnFactory');
  const newDataObject = bpmnFactory.create('bpmn:DataObject');

  newDataObject.name = dataObject.name;
  newDataObject.id = dataObject.id;
  newDataObject.itemSubjectRef = `xsd:${dataObject.itemSubjectRef}`;
  newDataObject.$attrs.inoutput = dataObject.inoutput;
  newDataObject.$attrs.required = dataObject.required;
  if (getBusinessObject(element).flowElements.find((e: Element) => e.id == newDataObject.id)) {
    ElMessage.error('变量标识已存在');
    throw new Error('变量标识已存在');
  }

  getBusinessObject(element).flowElements.push(newDataObject);
}

export function updateGlobalVariableValue(element: Element, dataObject: GlobalVariable) {
  const messageEvents = getBusinessObject(element).flowElements.filter((e: Element) => is(e, 'bpmn:DataObject'));

  const id = dataObject.id;
  const newDataObject = messageEvents.find((e: Element) => e.id == id);
  if (newDataObject) {
    newDataObject.name = dataObject.name;
    newDataObject.itemSubjectRef = `xsd:${dataObject.itemSubjectRef}`;
    newDataObject.$attrs.inoutput = dataObject.inoutput;
    newDataObject.$attrs.required = dataObject.required;
  } else {
    ElMessage.error('变量标识未存在');
    throw new Error('变量标识未存在');
  }
}

export function deleteGlobalVariableValue(element: Element, dataObject: GlobalVariable) {
  const flowElements = getBusinessObject(element).flowElements;

  const id = dataObject.id;
  const dataObjectIndex = flowElements.findIndex((e: Element) => is(e, 'bpmn:DataObject') && e.id == id);
  if (dataObjectIndex > -1) {
    flowElements.splice(dataObjectIndex, 1);
  } else {
    ElMessage.error('变量标识未存在');
    throw new Error('变量标识未存在');
  }
}
